//
//  View+Opt.swift
//  SwiftuiZsa
//
//  Created by hccc on 2023/7/24.
//

import SwiftUI

extension View {
    @ViewBuilder
    func ifCondition<T, Content: View>(_ value: T?, @ViewBuilder transform: @escaping (Self, T) -> Content) -> some View {
        if let unwrappedValue = value {
            transform(self, unwrappedValue)
        } else {
            self
        }
    }
    
    @ViewBuilder
    func ifIs<T>(_ condition: Bool, transform: (Self) -> T) -> some View where T: View {
        if condition {
            transform(self)
        } else {
            self
        }
    }
    
    @ViewBuilder
    func ifBolckIs<Content: View>(_ condition: () -> (Bool), transform: (Self) -> Content) -> some View {
        if condition() {
            transform(self)
        } else {
            self
        }
    }
    
    
    @ViewBuilder func iPhone<T>(_ transform: (Self) -> T) -> some View where T: View {
        if deviceType == .iphone {
            transform(self)
        } else {
            self
        }
    }
    
    @ViewBuilder func iPad<T>(_ transform: (Self) -> T) -> some View where T: View {
        if deviceType == .ipad {
            transform(self)
        } else {
            self
        }
    }
    
    @ViewBuilder func mac<T>(_ transform: (Self) -> T) -> some View where T: View {
        if deviceType == .mac {
            transform(self)
        } else {
            self
        }
    }
    
    @ViewBuilder func iPadOrMac<T>(_ transform: (Self) -> T) -> some View where T: View {
        if deviceType == .mac || deviceType == .ipad {
            transform(self)
        } else {
            self
        }
    }
}

fileprivate enum DeviceType {
    case iphone
    case ipad
    case mac
}

fileprivate var deviceType: DeviceType = {
#if targetEnvironment(macCatalyst)
    return .mac
#else
    if UIDevice.current.userInterfaceIdiom == .pad {
        return .ipad
    } else {
        return .iphone
    }
#endif
}()
